package study.reflection;

import java.lang.reflect.Method;
import java.util.*;

public class Reflection {
    public static void printClassInfo(Class cls) {
        System.out.println("Class name: " + cls.getName());
        System.out.println("Simple name: " + cls.getSimpleName());
        if (cls.getPackage() != null) {
            System.out.println("Package name: " + cls.getPackage().getName());
        }
        System.out.println("is interface: " + cls.isInterface());
        System.out.println("is enum: " + cls.isEnum());
        System.out.println("is array: " + cls.isArray());
        System.out.println("is primitive: " + cls.isPrimitive());
        System.out.println("is class: " + cls.isAnonymousClass());
        System.out.println("is MemberClass: " + cls.isMemberClass());
        System.out.println("is LocalClass: " + cls.isLocalClass());
        Arrays.stream(cls.getFields()).forEach(field -> {
            System.out.println(field.getName());
            System.out.println(field.getType());
        });
        System.out.println();
    }

    /**
     * 根据枚举的字符串获取枚举的值
     *
     * @param className 包名+类名
     * @return List<Map < String, Object>>
     * @link https://blog.csdn.net/SunFlowerXT/article/details/90035512
     */
    public static List<Map<String, Object>> getAllEnumByClassName(String className) throws Exception {
        // 1.得到枚举类对象
        Class<Enum> clz = (Class<Enum>) Class.forName(className);
        // 2.得到所有枚举常量
        Object[] objects = clz.getEnumConstants();
        Method getValue = clz.getMethod("getValue");
        Method getDesc = clz.getMethod("getDesc");
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map = null;
        for (Object obj : objects) {
            map = new HashMap<String, Object>();
            map.put("value", getValue.invoke(obj));
            map.put("desc", getDesc.invoke(obj));
            list.add(map);
        }
        return list;
    }
}
